package com.cloud.gateway.config;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

/**
 * 自定义路由断言工厂
 *
 * @author H
 * @version 1.0
 * @date 2023-11-30 17:37
 */
@Component
public class AuthRoutePredicateFactory extends AbstractRoutePredicateFactory<AuthRoutePredicateFactory.Config> {
    public AuthRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return exchange -> {
            MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
            if (queryParams.get("name").get(0).equals(config.getName()) && queryParams.get("pwd").get(0).equals(config.getPwd())) {
                return true;
            }
            return false;
        };
    }

    /**
     * 路由断言工厂的读取字段的顺序
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("name", "pwd");
    }

    @Data
    public static class Config {
        private String name;
        private String pwd;

    }

}
